/**
 * Created by htzhanglong on 2015/8/2.
 */
angular.module('starter.controllers', [])

    .controller('todoCtrl', function($scope,$rootScope,ENV,TodoRepairOrderList,$ionicHistory,queryNum) {
        $scope.showloading=true;
        $scope.ENV=ENV;
        // 获取第一页数据
        TodoRepairOrderList.getTopOrders();


        $scope.$on('TodoOrderList.portalsUpdated', function() {

            queryNum.query();
            // $timeout(function() {
            $scope.orderListData = TodoRepairOrderList.getOrders();
            $scope.showloading=false;

            // }, 100);
        });

        $scope.doRefresh = function() {
            // queryNum.getTodoNum();
            TodoRepairOrderList.getTopOrders();
            $scope.$broadcast('scroll.refreshComplete');
        };

        $scope.loadMore = function() {
            console.log("loadMore");
            TodoRepairOrderList.getMoreOrders();
            $scope.$broadcast('scroll.infiniteScrollComplete');

        };
        $scope.moreDataCanBeLoaded = function() {
            //console.log(PortalsFactory.hasNextPage());
            return TodoRepairOrderList.hasNextPage();
        };
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        //

    })
    //报修详情
    .controller('detailCtrl', function($scope,$rootScope,ENV,$ionicModal,$state,$stateParams,$ionicPopover,$cordovaDevice,$ionicActionSheet,RepairOrderContent,$ionicLoading,$ionicHistory,$timeout,webview) {
        $scope.ENV=ENV.api.slice(0,ENV.api.length-1);
        $scope.showloading=false;
        $scope.img=[];
        // $scope.img.src="img/ionic.png";

        var aid=$stateParams.aid;
        RepairOrderContent.get(aid);

        $scope.doRefresh = function() {
            RepairOrderContent.get(aid);
            $scope.$broadcast('scroll.refreshComplete');
        };


        $scope.$on('RepairOrder.contentUpdated', function() {

            // $timeout(function() {
            $scope.orderDetail = RepairOrderContent.getArticle();
            if($scope.orderDetail.rapairPicUrls!=null){
              $scope.img=$scope.orderDetail.rapairPicUrls.split(",");
            }else {
              $scope.img="";
            }
            $scope.showloading=false;

            // }, 100);
        });

        //显示打电话actionsheet
        $scope.showSheet = function(data) {
            // 显示操作表
            console.log("电话"+data);
            $ionicActionSheet.show({
                buttons: [
                    { text: data },
                ],
                // destructiveText: 'Delete',
                cancelText: '取消',
                buttonClicked: function(index) {
                    console.log('dianji:'+data);
                    if($cordovaDevice.getPlatform()=="Android"){
                        document.location.href = 'tel:'+data;

                    }
                    else {
                        phonedialer.dial(data, function(err) {
                            if (err == "feature")
                                alert("Your device doesn't support this feature.");
                            if (err == "empty")
                                alert("Unknown phone number");
                        });


                    }
                }
            });

        };

        $scope.grab=function (id) {
            console.log("id"+id);
            RepairOrderContent.grab(id);
        };

        $scope.$on('RepairOrder.grabSuccess', function() {
            $scope.grabResult = RepairOrderContent.getGrabResult();
            console.log("grabResult"+$scope.grabResult);
            $ionicLoading.show({
                noBackdrop: true,
                template: $scope.grabResult.msg,
                duration: 1500
            });

            $timeout(function(){
                // $ionicHistory.goBack();
                $state.go("tab.todo",{},{reload:true});
            },1500);
        });

        //返回
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        $ionicModal.fromTemplateUrl('modal.html', function (modal) {
            $scope.modal = modal;
        }, {
            animation: 'slide-in-left',
            focusFirstInput: true
        });

        $scope.showBigPic=function(src){
            $scope.modal.src=src;
            console.log(src);
            $scope.modal.show();

        }
        $scope.openWeb=function(param){
            webview.openWeb(param);
        }

    })
    //跟进详情
    .controller('followDetailCtrl', function($scope,$rootScope,ENV,TurnTransfor,$ionicPopup,startRepair,$cordovaDevice,RepairNode,$ionicModal,$stateParams,$ionicPopover,$ionicActionSheet,$ionicHistory,RepairOrderContent,TurnException,$state,Toast,webview,popupService) {
        $scope.url=ENV.api.substring(0,ENV.api.length-1);
        $scope.showloading=false;
        $scope.orderDetail={};
        $scope.aid=$stateParams.aid;
        $scope.orderId=$stateParams.orderId;
        $scope.img=[];
        $scope.turnContent='';      //上报理由
        // $scope.message.report='';

        // console.log("id是："+aid+"$scope.orderDetail:"+$scope.orderDetail);
        RepairOrderContent.get($scope.aid); //获取订单详情
        RepairNode.getRepairNodes($scope.orderId);
        $scope.$on('RepairOrder.contentUpdated', function() {

            $scope.orderDetail = RepairOrderContent.getArticle();
            if($scope.orderDetail.rapairPicUrls !=null){
                $scope.img=$scope.orderDetail.rapairPicUrls.split(",");
            }
            else{
                $scope.img="";
            }


            $scope.showloading=false;
        });

        $scope.$on('RepairOrder.nodeSuccessEd', function() {

            $scope.repairNodes= RepairNode.getNodes();

        });


        $scope.doRefresh = function() {
            RepairOrderContent.get($scope.aid);
            RepairNode.getRepairNodes($scope.orderId);
            $scope.$broadcast('scroll.refreshComplete');
        };


        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        $ionicPopover.fromTemplateUrl("ez-popover.html", {
            scope: $scope
        })
            .then(function(popover){
                $scope.popover = popover;
            });
        $scope.openPopover = function($event) {

            $scope.popover.show($event);
        };
        $scope.closePopover = function() {
            $scope.popover.hide();

        };
        //销毁事件回调处理：清理popover对象
        $scope.$on("$destroy", function() {
            $scope.popover.remove();
        });
        // 隐藏事件回调处理
        $scope.$on("popover.hidden", function() {
            // Execute action
        });
        //删除事件回调处理
        $scope.$on("popover.removed", function() {
            // Execute action
        });

        //显示打电话actionsheet
        $scope.show = function(tel) {
            // 显示操作表
            console.log("电话"+tel);
            $ionicActionSheet.show({
                buttons: [
                    { text: tel },
                ],
                // destructiveText: 'Delete',
                cancelText: '取消',
                buttonClicked: function(index) {
                    return true;
                }
            });

        };



        $scope.grab=function (id) {
            console.log("id"+id);
        }
        // //弹出转单确认框
        // $scope.showConfirm = function() {
        //     $ionicPopup.confirm({
        //         title: "转单申请",
        //         template: "确定转单吗？",
        //         okText:"确定",
        //         cancelText:"取消"
        //     })
        //         .then(function(res) {
        //             console.log("确认框的结果为："+res);
        //             if(res) {
        //                 // $scope.status = "凭什么吃我的冰淇淋！";
        //                 TurnTransfor.putTransfor($scope.aid,'');
        //                 $scope.popover.hide();
        //             } else {
        //                 // $scope.status = "谢谢你不吃之恩！";
        //                 $scope.popover.hide();
        //             }
        //         });
        // };

        //弹出警告框
        $scope.showAlert = function(msg) {
            $ionicPopup.alert({
                title: "提示",
                template:msg
            })
                .then(function(res) {
                    // $scope.status = "感谢上帝";
                });
        };

        //上报
        $scope.report = function() {
            //弹出上报和转单的确认框
            $scope.message={};
            $ionicPopup.show({
                template: "<input type='text' ng-model='message.report'>",
                title: "请输入上报理由",
                // subTitle: "密码为8位",
                scope: $scope,
                buttons: [
                    {text: "取消",
                    onTap: function (e) {
                      return true;
                    }
                    },
                    {
                        text: "<b>提交</b>",
                        type: "button-positive",
                        onTap: function (e) {
                            return $scope.message.report;
                        }
                    }
                ]
            })
                .then(function (res) {
                    //发送提交申请
                    console.log(res);
                  if(res==''||res==undefined){
                    $scope.showAlert("必须填写理由才能提交哦");
                  }
                  else if(res==true){

                  }
                  else{
                    TurnException.putException($scope.aid,res);
                  }

                });
        }

        // 转单
        $scope.transfor = function() {
          //提交转单
          $scope.message={};
          var myPopup=$ionicPopup.show({
            template: "<input type='text' ng-model='message.report'>",
            title: "请输入转单理由",
            // subTitle: "密码为8位",
            scope: $scope,
            buttons: [
              {text: "取消",
                onTap: function (e) {
                  return true;
                }
              },
              {
                text: "<b>提交</b>",
                type: "button-positive",
                onTap: function (e) {
                  return $scope.message.report;
                }
              }
            ]
          });

          myPopup.then(function (res) {
              //发送提交申请
              console.log("ceshi"+res);

              if(res==''||res==undefined){
                $scope.showAlert("必须填写理由才能转单哦");
              }
              else if(res==true){
                myPopup.close();
              }
              else{
                TurnTransfor.putTransfor($scope.aid,res);
              }

              // $scope.turnContent=res;
            },function (err) {
              console.log('Err:', err);
            }, function (msg) {
              console.log('message:', msg);

            });
        }







      // //转单
      // $scope.transfor = function() {
      //   //提交转单
      //   $scope.message={};
      //   popupService.show('show',
      //     {
      //     template: "<input type='text' ng-model='message.report'>",
      //     title: "请输入转单理由",
      //     // subTitle: "密码为8位",
      //     scope: $scope,
      //     buttons: [
      //       {text: "取消",
      //         onTap: function (e) {
      //           return true;
      //         }
      //       },
      //       {
      //         text: "<b>提交</b>",
      //         type: "button-positive",
      //         onTap: function (e) {
      //           return $scope.message.report;
      //         }
      //       }
      //     ]
      //   })
      //     .then(function (res) {
      //       //发送提交申请
      //       console.log(res);
      //
      //       if(res==''||res==undefined){
      //         $scope.showAlert("必须填写理由才能转单哦");
      //       }
      //       else if(res==true){
      //
      //       }
      //       else{
      //         TurnTransfor.putTransfor($scope.aid,res);
      //       }
      //
      //       // $scope.turnContent=res;
      //     },function (err) {
      //       console.log('Err:', err);
      //     }, function (msg) {
      //       console.log('message:', msg);
      //
      //     });
      // }




        //上报成功后，返回
        $scope.$on('RepairOrder.ExceptionEd', function() {
            $state.go("tab.task");
        });
        $scope.$on('RepairOrder.PutTurnEd', function() {
            $state.go("tab.task");
        });
        //监听到结束
        $scope.$on('RepairOrder.Finished', function() {
            $state.go("tab.task");
        });


        $ionicModal.fromTemplateUrl('modal_follw.html', function (modal) {
            $scope.modal = modal;
        }, {
            animation: 'slide-in-left',
            focusFirstInput: true
        });
        $scope.showBigPic=function(src){
            //点击开始维修
            $scope.modal.src=src;
            console.log(src);

            $scope.modal.show();
        }
        $scope.startRepair=function(id){
            startRepair.start(id);
        }

        $scope.$on('StartRepair.Started', function() {
            $state.go("tab.task");
        });

        //显示打电话actionsheet
        $scope.showSheet = function(data) {
            // 显示操作表
            console.log("电话"+data);
            $ionicActionSheet.show({
                buttons: [
                    { text: data },
                ],
                // destructiveText: 'Delete',
                cancelText: '取消',
                buttonClicked: function(index) {
                    console.log('dianji:'+data);
                    if($cordovaDevice.getPlatform()=="Android"){
                        document.location.href = 'tel:'+data;

                    }
                    else {
                        phonedialer.dial(data, function(err) {
                            if (err == "feature")
                                alert("Your device doesn't support this feature.");
                            if (err == "empty")
                                alert("Unknown phone number");
                        });


                    }
                }
            });

        };


        //点击结束
        //弹出转单确认框
        $scope.finishConfirm = function() {
            $ionicPopup.confirm({
                title: "结束维修",
                template: "确定结束吗？",
                okText:"确定",
                cancelText:"取消"
            })
                .then(function(res) {
                    if(res) {
                        TurnTransfor.finishOrder($scope.aid);
                        $scope.popover.hide();
                    } else {
                        // $scope.status = "谢谢你不吃之恩！";
                        $scope.popover.hide();
                    }
                });
        };

        $scope.openWeb=function(param){
          webview.openWeb(param);
        }

    })
    .controller('knowledgeCtrl', function($scope,$rootScope,ENV,$ionicHistory,$cordovaDevice) {


        // $scope.back = function(){
        //     $ionicHistory.goBack();
        //     console.log("back");
        // };
        $scope.openWeb=function() {
            if($cordovaDevice.getPlatform()=="Android"){
                cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?do=search&id=%E5%93%88%E5%93%88%E5%93%88', '_blank', {
                    statusbar: {
                        color: '#444444'
                    },
                    toolbar: {
                        height: 44,
                        color: '#383838'
                    },
                    title: {
                        color: '#ffffff',
                        staticText: '',
                        showPageTitle: false
                    },
                    backButton: {
                        image: 'back',
                        imagePressed: 'back_pressed',
                        align: 'left',
                        event: 'backPressed'
                    },
                    // customButtons: [
                    //   {
                    //     image: 'share',
                    //     imagePressed: 'share_pressed',
                    //     align: 'right',
                    //     event: 'sharePressed'
                    //   }
                    // ],
                    // menu: {
                    //   image: 'menu',
                    //   imagePressed: 'menu_pressed',
                    //   title: 'Test',
                    //   cancel: 'Cancel',
                    //   align: 'right',
                    //   items: [
                    //     {
                    //       event: 'helloPressed',
                    //       label: 'Hello World!'
                    //     },
                    //     {
                    //       event: 'testPressed',
                    //       label: 'Test!'
                    //     }
                    //   ]
                    // },
                    backButtonCanClose: true
                }).addEventListener('backPressed', function (e) {
                    // alert('back pressed');
                }).addEventListener('helloPressed', function (e) {
                    alert('hello pressed');
                }).addEventListener('sharePressed', function (e) {
                    alert(e.url);
                }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
                    console.error(e.message);
                }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
                    console.log(e.message);
                });
            }
            else{
                $scope.openWeb=function() {
                    cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?do=search&id=%E5%93%88%E5%93%88%E5%93%88', '_blank', {
                        statusbar: {
                            color: '#444444'
                        },
                        toolbar: {
                            height: 44,
                            color: '#444444'
                        },
                        title: {
                            color: '#ffffff',
                            staticText: '知识库',
                            showPageTitle: false
                        },
                        backButton: {
                            wwwImage: 'img/back_ios.png',
                            wwwImagePressed: 'back_pressed',
                            align: 'left',
                            event: 'backPressed'
                        },
                        //customButtons: [
                        //  {
                        //    image: 'share',
                        //    imagePressed: 'share_pressed',
                        //    align: 'right',
                        //    event: 'sharePressed'
                        //  }
                        //],
                        //menu: {
                        //  image: 'menu',
                        //  imagePressed: 'menu_pressed',
                        //  title: 'Test',
                        //  cancel: 'Cancel',
                        //  align: 'right',
                        //  items: [
                        //    {
                        //      event: 'helloPressed',
                        //      label: 'Hello World!'
                        //    },
                        //    {
                        //      event: 'testPressed',
                        //      label: 'Test!'
                        //    }
                        //  ]
                        //},
                        backButtonCanClose: true
                    }).addEventListener('backPressed', function (e) {
                        // alert('back pressed');
                    }).addEventListener('helloPressed', function (e) {
                        alert('hello pressed');
                    }).addEventListener('sharePressed', function (e) {
                        alert(e.url);
                    }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
                        console.error(e.message);
                    }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
                        console.log(e.message);
                    });
                }

            }

        }

        $scope.openWeb();

    })

    // .controller('taskCtrl', function($scope,$rootScope,TaskList,$ionicHistory) {
    //     // $scope.showloading=true;
    //     $scope.status=0;
    //     var lock=false;
    //
    //     $scope.loadMoreTask = function() {
    //       if(lock){
    //         console.log("loadMoreTask");
    //         TaskList.getMoreList();
    //       }
    //       $scope.$broadcast('scroll.infiniteScrollComplete');
    //       lock=true;
    //     };
    //
    //     $scope.changeTab = function(status,index) {
    //         $scope.status=status;
    //         var a=document.getElementById('sub_header_list').getElementsByTagName('a');
    //         for (var i = 0; i < 3; i++) {
    //             a[i].className = "button button-clear ";
    //         }
    //         a[index].className = "button button-clear sub_button_select";
    //         console.log("status的值："+TaskList.getCurrentStatus());
    //         TaskList.setOrderStatus(status,0);
    //
    //     };
    //     TaskList.setOrderStatus(0,0);//获取第一页数据
    //
    //     $scope.$on('TaskList.listUpdated', function() {
    //
    //         console.log("检测到更新完毕");
    //           $scope.taskListData = TaskList.getList();
    //           // console.log("$scope.taskListData:"+$scope.taskListData);
    //           $scope.showloading = false;
    //     });
    //
    //     $scope.doRefresh = function() {
    //         TaskList.setOrderStatus($scope.status,0);
    //         $scope.$broadcast('scroll.refreshComplete');
    //     };
    //     $scope.back = function(){
    //         $ionicHistory.goBack();
    //         console.log("back");
    //     };
    //
    //
    //
    //     $scope.moreDataCanBeLoaded = function() {
    //       //console.log(PortalsFactory.hasNextPage());
    //       return TaskList.hasNextPage();
    //     };
    //
    // })


    .controller('taskCtrl2', function($scope,$rootScope,TaskList2,$ionicHistory,$ionicSlideBoxDelegate,$ionicTabsDelegate) {

        $scope.back = function(){
          $ionicHistory.goBack();
          console.log("back");
        };


        $scope.showloading = false;

        var classify = TaskList2.getTasks();



        $scope.slides = classify;
        $scope.tabs = classify;
        console.log("------------------------");



        var getData = function (index) {
          var c = classify[index];
          // 安卓平台不会自动触发加载
          // if (ionic.Platform.isAndroid()) {
            c.getTopList();
            // c.isload=false;
            // $scope.$broadcast('scroll.infiniteScrollComplete');
          // }
          // // 初始化数据，和回调函数
          // c.isload = false;
          // c.callback = function () {
          //   $scope.$broadcast('scroll.refreshComplete');
          //   $scope.$broadcast('scroll.infiniteScrollComplete');
          // }
        }
        getData(0);

        console.log($scope.slides);

        $scope.slideChanged = function (index) {
          getData(index);
          //这里使用instances[1]的原因是视图中有两个tabs
          $ionicTabsDelegate._instances[1].select(index);
        };

        $scope.$on('$ionicView.afterEnter', function () {
          //等待视图加载完成的时候默认选中第一个菜单
          $ionicTabsDelegate._instances[1].select($ionicSlideBoxDelegate.currentIndex());
        });

        $scope.selectedTab = function (index) {
          //滑动的索引和速度
          $ionicSlideBoxDelegate.slide(index)
        }


        $scope.$on('TaskList.refreshed', function() {
          console.log("检测下拉刷新到更新完毕");
          $scope.$broadcast('scroll.refreshComplete');
        });
  })


    .controller('userCtrl', function($scope,$state,Storage,User,$rootScope,$ionicHistory,$stateParams,modifyInfo,Toast,modifyPassword) {

        var storageKey='user';
        console.log("localStorage"+Storage.get('user'));

        $scope.uid=$stateParams.uid;
        console.log($scope.uid);
        //每次加载前 判断是否登录
        $scope.$on('$ionicView.beforeEnter', function() {
            if(Storage.get(storageKey)&&Storage.get(storageKey).username!=''){
                $scope.userInfo=Storage.get(storageKey);
                console.log("userInfo"+$scope.userInfo);
            }else{
                $scope.userInfo='';
                $state.go('signin');  //路由跳转
            }
        });

        //退出登录
        $scope.logOut=function(){
            User.logout();
            $state.go('signin');  //路由跳转
        }

        //回退
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };


        $scope.jobType=[{name:'泥瓦',value:0,isCheck:false},{name:'涂料油漆',value:1,isCheck:false},{name:'蜘蛛人',value:2,isCheck:false},{name:'木工',value:3,isCheck:false},{name:'木作',value:4,isCheck:false},{name:'铁艺油漆',value:5,isCheck:false},
            {name:'粘贴壁纸',value:6,isCheck:false},{name:'石材修补',value:7,isCheck:false},{name:'电工',value:8,isCheck:false},{name:'管道工',value:9,isCheck:false},{name:'锁匠',value:10,isCheck:false},{name:'门窗制安',value:11,isCheck:false},{name:'收纳安装',value:12,isCheck:false},{name:'杂工',value:13,isCheck:false}]
        if(Storage.get(storageKey).goodAtWork!=null){
            var goodAtWork=Storage.get(storageKey).goodAtWork.split(',');//将擅长工种转化为数组

            goodAtWork.forEach(function(item1,index){
                $scope.jobType.forEach(function(item2,index){
                    if(item1==item2.name){
                        item2.isCheck=true
                    }
                })
            })

        }

        //修改工种
        $scope.modifyJobType=function(){
            var goodAtWork='';
            $scope.jobType.forEach(function(item,index){
                if(item.isCheck==true){
                    goodAtWork+=item.name+",";
                }
            })
            goodAtWork=goodAtWork.substr(0,goodAtWork.length-1);

            modifyInfo.modifyJobType(goodAtWork);
        }

        $scope.password={};

        //修改密码
        $scope.modifyPassword=function(){
            if($scope.password.oldPassword==undefined){
                Toast.show("请输入当前密码！");
            }
            else if($scope.password.newPassword==undefined){
                Toast.show("请输入新密码！");
            }
            else if($scope.password.newPassword!=$scope.password.newPassword2){
                Toast.show("新密码两次输入不一致！");
            }
            else{
                modifyPassword.sendModify($scope.password.oldPassword,$scope.password.newPassword);
            }

        }






    })

    //用户登录
    .controller('loginCtrl', function($scope,$state,$ionicLoading,User,Storage,$rootScope,$ionicHistory,CheckLogin,$ionicPopup) {

        console.log("打开app");

        //判断session是否已经失效
        $scope.checkLogin=function(){
            console.log("发送验证session的请求");
            CheckLogin.checkLogin(Storage.get("sessionId"));
        };
        $scope.checkLogin();

        $rootScope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };
        var storageKey='user';
        // $scope.$on('$ionicView.beforeEnter', function() {
        //     console.log("试图加载前运行：");
        //     if(Storage.get(storageKey)&&Storage.get(storageKey).username!=''&&Storage.get("sessionId")!=''){
        //         $scope.checkLogin();
        //     }
        //
        // });
        //检验请求发送成功后
        $scope.$on('User.CheckLoginUpdated', function() {
            console.log("检测session的结果："+CheckLogin.getResult().msg);
            if(CheckLogin.getResult().success){
                console.log("新的sessionId"+CheckLogin.getResult().newSessionId);
                Storage.set("sessionId",CheckLogin.getResult().newSessionId);
                $state.go('tab.user');  //路由跳转
            }
            // else{
            //     $state.go('signin');  //路由跳转
            // }
        })



        var storageKey='user';
        //一定要注意定义 我们的ng-model的对象 数据
        $scope.user={
            loginName:'',
            password:''
        }

        //用户登录
        $scope.signIn=function(){
            console.log($scope.user);
            User.login($scope.user.loginName,$scope.user.password);

        }
        //登录后
        $scope.$on('User.loginUpdated', function() {
            var userRel = User.getCurrentUser();
            console.log("userRel"+userRel);
            if(userRel.success==false||userRel==undefined){//登陆失败
                //    alert(userRel.message);
                $ionicLoading.show({
                    noBackdrop: true,
                    template: userRel.msg,
                    duration: 1500
                });
            }else{
                console.log("用户的sessonId："+userRel.sessionId);
                Storage.set(storageKey,userRel.currentUser);
                Storage.set("sessionId",userRel.sessionId);
                $state.go('tab.user');  //路由跳转

            }

        });

        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

       //点击忘记密码弹窗
        $scope.forgetPassword = function() {
          var alertPopup = $ionicPopup.alert({
            title: '提示',
            template: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请联系工作人员'
          });
          alertPopup.then(function(res) {
            console.log('Thank you for not eating my delicious ice cream cone');
          });
        };





    })
    //我的维修记录
    .controller('repairRecordCtrl', function($scope,$rootScope,TaskList,$ionicHistory) {

        $scope.showloading=false;
        var lock=false;
        $scope.icon_arrow={mark_left:true,mark_right:true,value_left:'ion-arrow-down-b',value_right:'ion-arrow-down-b',font_color_left:'',font_color_left:'',
            is_show_left:false,is_show_right:false};
        $scope.timeValue='时间排序';
        $scope.statusValue='状态';
        $scope.status=0;
        $scope.flag=0;
        $scope.choseSelect=function(i){
            console.log('timeValue'+$scope.timeValue);
            if(i==2){
                $scope.icon_arrow.mark_left=!$scope.icon_arrow.mark_left;
                if($scope.icon_arrow.mark_left){          //左边关闭
                    $scope.icon_arrow.value_left='ion-arrow-down-b';
                    $scope.font_color_left='';
                    $scope.icon_arrow.is_show_left=false;
                }
                else{
                    $scope.icon_arrow.value_left='ion-arrow-up-b';
                    $scope.font_color_left='font_color_left';
                    $scope.icon_arrow.value_right='ion-arrow-down-b';
                    $scope.font_color_right='';
                    $scope.icon_arrow.is_show_right=false;
                    $scope.icon_arrow.mark_right=true;
                    $scope.icon_arrow.is_show_left=true;
                }
            }
            else{
                $scope.icon_arrow.mark_right=!$scope.icon_arrow.mark_right;
                if($scope.icon_arrow.mark_right){          //右边关闭
                    $scope.icon_arrow.value_right='ion-arrow-down-b';
                    $scope.font_color_right='';
                    $scope.icon_arrow.is_show_right=false;
                }
                else{
                    $scope.icon_arrow.value_right='ion-arrow-up-b';
                    $scope.font_color_right='font_color_right';
                    $scope.icon_arrow.value_left='ion-arrow-down-b';
                    $scope.font_color_left='';
                    $scope.icon_arrow.is_show_right=true;
                    $scope.icon_arrow.mark_left=true;
                    $scope.icon_arrow.is_show_left=false;
                }
            }
        }
        $scope.hideModalLeft=function(){
            $scope.icon_arrow.is_show_left=false;
        }
        $scope.hideModalRight=function(){
            $scope.icon_arrow.is_show_right=false;
        }

        $scope.$watch('timeValue',function(newValue,oldValue, scope){

            if (newValue !=oldValue) {
                $scope.icon_arrow.is_show_left=false;
                $scope.icon_arrow.value_left='ion-arrow-down-b';
                $scope.font_color_left='';
                $scope.icon_arrow.mark_left=true;


            }
            if( $scope.timeValue=='时间升序'){
                $scope.flag=1;
            }
            else if($scope.timeValue=='时间降序'){
                $scope.flag=0;
            }

            TaskList.setOrderStatus($scope.status, $scope.flag);


        });

        $scope.$watch('statusValue',function(newValue,oldValue, scope){

            if (newValue !=oldValue) {
                $scope.icon_arrow.is_show_right=false;
                $scope.icon_arrow.value_right='ion-arrow-down-b';
                $scope.font_color_right='';
                $scope.icon_arrow.mark_right=true;
            }

            if( $scope.statusValue=='已完成'){
                $scope.status=2;

            }
            else if( $scope.statusValue=='进行中'){
                $scope.status=1;
            }
            else if( $scope.statusValue=='异常件'){
                $scope.status=4;
            }
            else if( $scope.statusValue=='已转单'){
                $scope.status=3;
            }
            else if( $scope.statusValue=='待联系'){
                $scope.status=0;
            }

            TaskList.setOrderStatus($scope.status, $scope.flag);

        });

        $scope.$on('TaskList.listUpdated', function() {

            console.log("检测到更新完毕");
            $scope.taskListData = TaskList.getList();
            $scope.listNum=TaskList.getListNum();
            console.log("$scope.taskListData:"+$scope.taskListData);
            $scope.showloading=false;
        });

        $scope.doRefresh = function() {
            TaskList.setOrderStatus($scope.status, $scope.flag);
            $scope.$broadcast('scroll.refreshComplete');
        };

        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        $scope.loadMore = function() {
          console.log("loadMore");
          if(lock){
            TaskList.getMoreList();
          }
          $scope.$broadcast('scroll.infiniteScrollComplete');
          lock=true;
        };

        $scope.moreDataCanBeLoaded = function() {
          //console.log(PortalsFactory.hasNextPage());
          return TaskList.hasNextPage();
        };






    })

    .controller('tabCtrl',function($scope,queryNum,$cordovaDevice){
        console.log("tabCtrl");
        $scope.todoNum=0;
        $scope.taskNum=0;
        queryNum.query();
        $scope.$on('queryNum.Success', function() {
            $scope.todoNum=queryNum.getTodoNum();

        })
        $scope.openWeb=function() {

            if($cordovaDevice.getPlatform()=="Android"){

                cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?id=start&do=index', '_blank', {
                    statusbar: {
                        color: '#444444'
                    },
                    toolbar: {
                        height: 44,
                        color: '#444444'
                    },
                    title: {
                        color: '#ffffff',
                        staticText: '知识库',
                        showPageTitle: false
                    },
                    backButton: {
                        image: 'back',
                        imagePressed: 'back_pressed',
                        align: 'left',
                        event: 'backPressed'
                    },
                    // customButtons: [
                    //   {
                    //     image: 'share',
                    //     imagePressed: 'share_pressed',
                    //     align: 'right',
                    //     event: 'sharePressed'
                    //   }
                    // ],
                    // menu: {
                    //   image: 'menu',
                    //   imagePressed: 'menu_pressed',
                    //   title: 'Test',
                    //   cancel: 'Cancel',
                    //   align: 'right',
                    //   items: [
                    //     {
                    //       event: 'helloPressed',
                    //       label: 'Hello World!'
                    //     },
                    //     {
                    //       event: 'testPressed',
                    //       label: 'Test!'
                    //     }
                    //   ]
                    // },
                    backButtonCanClose: true
                }).addEventListener('backPressed', function (e) {
                    // alert('back pressed');
                }).addEventListener('helloPressed', function (e) {
                    alert('hello pressed');
                }).addEventListener('sharePressed', function (e) {
                    alert(e.url);
                }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
                    console.error(e.message);
                }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
                    console.log(e.message);
                });
            }
            else{
                cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?id=start&do=index', '_blank', {
                    statusbar: {
                        color: '#444444'
                    },
                    toolbar: {
                        height: 44,
                        color: '#444444'
                    },
                    title: {
                        color: '#ffffff',
                        staticText: '知识库',
                        showPageTitle: false
                    },
                    backButton: {
                        wwwImage: 'img/back_ios.png',
                        wwwImagePressed: 'back_pressed',
                        align: 'left',
                        event: 'backPressed'
                    },
                    // customButtons: [
                    //   {
                    //     image: 'share',
                    //     imagePressed: 'share_pressed',
                    //     align: 'right',
                    //     event: 'sharePressed'
                    //   }
                    // ],
                    // menu: {
                    //   image: 'menu',
                    //   imagePressed: 'menu_pressed',
                    //   title: 'Test',
                    //   cancel: 'Cancel',
                    //   align: 'right',
                    //   items: [
                    //     {
                    //       event: 'helloPressed',
                    //       label: 'Hello World!'
                    //     },
                    //     {
                    //       event: 'testPressed',
                    //       label: 'Test!'
                    //     }
                    //   ]
                    // },
                    backButtonCanClose: true
                }).addEventListener('backPressed', function (e) {
                    // alert('back pressed');
                }).addEventListener('helloPressed', function (e) {
                    alert('hello pressed');
                }).addEventListener('sharePressed', function (e) {
                    alert(e.url);
                }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
                    console.error(e.message);
                }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
                    console.log(e.message);
                });
            }
        }


    })
    .controller('nodeReportCtrl',function($scope,$stateParams,$ionicModal,$cordovaImagePicker,$cordovaCamera,$timeout,$ionicHistory,$ionicActionSheet,Toast,FileUtil,SubmitNodeReport,$rootScope,Load){
        $scope.orderNum=$stateParams.aid;
        $scope.repairOrder={};
        $scope.repairOrder.repairStageContent='';
        // console.log("上传检修点报告："+aid);
        $scope.imgList=[];


        //  "添加附件"Event  
        $scope.addAttachment = function() {
            // nonePopover();
            $ionicActionSheet.show({
                buttons: [
                    { text: '相机' },
                    { text: '图库' }
                ],
                cancelText: '关闭',
                cancel: function() {
                    return true;
                },
                buttonClicked: function(index) {

                    switch (index){

                        case 0:
                            $scope.appendByCamera();
                            break;
                        case 1:
                            $scope.pickImage();
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
        }


        $scope.appendByCamera=function(){
            document.addEventListener("deviceready", function () {
                //拍照
                var options = {
                    quality: 50,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    allowEdit: false,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 100,
                    targetHeight: 100,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: true,
                    correctOrientation: true
                };
                $cordovaCamera.getPicture(options).then(function (imageData) {
                    // $scope.data.imageSrc = "data:image/jpeg;base64," + imageData;
                    $scope.imgList.unshift("data:image/jpeg;base64," + imageData);
                }, function (err) {
                    // error
                });
            }, false);

        }
        //image picker  
        $scope.pickImage=function () {
            var options = {
                maximumImagesCount: 4,
                width: 800,
                height: 800,
                quality: 80
            };

            $cordovaImagePicker.getPictures(options)
                .then(function (results) {
                    if(results.length+$scope.imgList.length>4){
                        Toast.show("最多上传4张照片！");
                    }else {
                        for(var i=0;i<results.length;i++){
                            $scope.imgList.unshift(results[i]);
                        }
                    }
                }, function (error) {
                    // error getting photos  
                });

        }
        //上传照片
        $scope.submitNode=function(){
            if($scope.repairOrder.repairStageContent==''){
                Toast.show('请填写节点报告');

            }
            else if($scope.imgList.length==0){
                Toast.show('请选择照片上传');
            }
            else{

                for(var i=0;i< $scope.imgList.length;i++){
                    Load.loading("正在提交...");
                    FileUtil.upload( $scope.imgList[i]).then(function (response) {

                    },function (err) {
                        $ionicLoading.hide();
                        Toast.show("结果:"+err);
                    });
                }
            }

        }


        //监听上传成功后
        $scope.$on('RepairOrder.UploadSuccess', function() {
            if(FileUtil.getImgSrc().length==$scope.imgList.length){
                SubmitNodeReport.submit($scope.orderNum, $scope.repairOrder.repairStageContent,FileUtil.getImgSrc().toString());
            }

        })
        //监听节点报告提交成功
        $scope.$on('RepairOrder.NodeReportEd', function() {
            FileUtil.setImgSrc(); //上传成功后清空数组
            Toast.show("提交成功！");
            $timeout(function () {
                $ionicHistory.goBack();
            }, 1700);



        })
        //删除选中图片


        // $scope.deletePic=function () {
        //   console.log($scope.modal.index);
        //   $scope.imgList=$scope.imgList.slice($scope.modal.index);
        //   $scope.modal.hide();
        // }

        $ionicModal.fromTemplateUrl('modal.html', function (modal) {
            $scope.modal = modal;
            $scope.modal.deletePic=function () {
                console.log($scope.modal.index);
                $scope.imgList.splice($scope.modal.index,1);
                $scope.modal.hide();
            }
        }, {
            animation: 'slide-in-left',
            focusFirstInput: true
        });

        $scope.showBigPic=function(index){
            $scope.modal.src=$scope.imgList[index];
            $scope.modal.index=index;
            console.log(index);
            $scope.modal.show();

        }



    })
